import React, { Component} from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card,Button,Form,Select,Input,Row,Col,DatePicker,Upload,message } from 'antd';
import PropTypes from 'prop-types';
import { FormInstance } from 'antd/lib/form';
import PicturesWall from '../../goodAdd/tbas/picturesWall';
import { windowUrl } from '../../../../../../public/global';
import { getMd5,getToken} from '@/utils/utils';
import { UploadOutlined } from '@ant-design/icons';
import moment from "moment";
import {getDictOptionsByCode } from '@/support/common';
import { getOptAuthHeaders } from '@/utils/common';

const FormItem = Form.Item;
const { TextArea } = Input;
const status = ['未上架', '已上架', '已下架', '已作废'];
@connect((state: any) => ({
  menu: state.menu,
  basedata: state.basedata,
  goodAdd: state.goodAdd,
}))
class basicInfo extends Component<any, any> {
  formRef = React.createRef<FormInstance>();
  static contextTypes = {
    dicData: PropTypes.any,
  };

  constructor(props: any) {
    super(props);
    this.state = {
     pic: '',
     icon: '',
     fileList:[], // 压缩包
     goodsQrPic:'',
     brandOptions:[],
     seriesOptions: [],
     typeOptions: [],
     goodTypeOption: [],
    };
  }
  componentWillMount() {
    if(sessionStorage.getItem('goodBasicInfo')){
      const basicInfo = JSON.parse(sessionStorage.getItem('goodBasicInfo') || '{}');
      this.setState({
        pic: basicInfo.pic,
        icon: basicInfo.icon,
        goodsQrPic: basicInfo.goodsQrPic,
        fileList: basicInfo.goodsAttachmen ? this.convertValueToFile(basicInfo.goodsAttachment) : []
      })
    }
    this.props.dispatch({
      type: 'basedata/brandFetch',
      callback: (res:any) => {
        this.setState({ 
           brandOptions: res?.data?.map((item:any)=>{
            return {
              label: item.brandName,
              value: item.brandCode
            }
           }),
        });
       }
    })
  }
  // 压缩包数据回显   
  convertValueToFile = (url) => {
    const files = [];
    if (!(url === null)) {
        files.push({
          uid: url,
          name: url,
          status: 'done',
          response:{
           data:{
            fileUrl: url
           }
          },
          url:url,
        });
    }
    return files;
  };
  componentDidMount() {
    this.props.onRef(this)
    if(sessionStorage.getItem('goodBasicInfo')){
      const basicInfo = JSON.parse(sessionStorage.getItem('goodBasicInfo') || '{}');
      const brandId = basicInfo.brandId;
      const carSeries = basicInfo.carSeries;
      const goodsTypeId = basicInfo.goodsTypeId;
      let carTypes = basicInfo.carTypes === null ? undefined : Array.isArray(basicInfo.carTypes) ? basicInfo.carTypes : basicInfo.carTypes?.split(',');
      let goodsPlatform = basicInfo.goodsPlatform === null ? undefined : Array.isArray(basicInfo.goodsPlatform) ? basicInfo.goodsPlatform : basicInfo.goodsPlatform?.split(',');
      const basicInfoData = {
        ...basicInfo,
        brandId: {label:basicInfo.brandName, value: basicInfo.brandId},
        carTypes: carTypes,
        goodsPlatform:goodsPlatform,
        validDate: basicInfo.validDate == null ? null : moment(basicInfo.validDate) ,
        spuStatus:status[basicInfo.spuStatus] || '',
        isHot: basicInfo.isHot == null ? basicInfo.isHot : basicInfo.isHot.toString(),
      }
      this.formRef.current?.setFieldsValue(basicInfoData);
      this.getSeries(brandId);
      this.getType(brandId,carSeries);
      this.getGoodType(brandId);
      this.getAttributeList(goodsTypeId,brandId);
    }else{
      this.formRef.current?.resetFields;
    }
  }
  setPic = (url:any) => {
    this.setState({
      pic: url,
    });
  };
  setIcon = (url:any) => {
    this.setState({
      icon: url,
    });
  };
  setQrcode= (url:any) => {
    this.setState({
      goodsQrPic: url,
    });
  };
  // 压缩包上传
  handleFileChange = (info:any) => {
    let tempFileList = info.fileList;
    tempFileList = tempFileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.statusCode === '0') {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'done' && info.file.response && info.file.response.statusCode !== '0') {
      message.error(`${info.file.response.message}`);
      this.setState({fileList: [] });
      return;
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
      this.setState({fileList: [] });
      return;
    } else if (!info.file.status) {
      this.setState({fileList: [] });
      return;
    }
    this.setState({ fileList: tempFileList });
  };
  beforeFileUpload = (file:any) => {
    if (file.size / 1024 / 1024> 20) {
      message.error('压缩包大小不能大于20MB!');
      return false;
    }
    else {
      return true;
    }
  };
  nextPage = () =>{
    this.saveValue();
    this.props.nextStep();
   }
   saveValue =()=>{
    this.formRef.current?.validateFields().then((values:any) => {
    const params = {
      ...values,
      pic: this.state.pic,
      icon: this.state.icon,
      goodsQrPic: this.state.goodsQrPic,
      fileList: this.state.fileList,
      brandId: values.brandId.value,
      brandName: values.brandId.label,
    }
    if(values.validDate){
      params.validDate =  moment(values.validDate?.milliseconds(0).second(59).minute(59).hour(23)).format('YYYY-MM-DD HH:mm:ss')
    }
    sessionStorage.setItem('goodBasicInfo', JSON.stringify(params));
    })
   }
  ok = (values:any) =>{
  }
  onBrandChange=(val:any)=>{
    this.formRef.current?.resetFields(['carSeries', 'carTypes','goodsTypeId']);
    this.setState({ seriesOptions: [], typeOptions: [], goodTypeOption: [], });
    const brandId = this.formRef.current?.getFieldValue('brandId');
    brandId &&
      this.props.dispatch({
        type: 'goodAdd/getDataWithRes',
        payload: {
          url: '/common/vehicle/getserieslist',
          brandId: val.value,
        },
        callback: (e:any) => {
          this.setState({
            seriesOptions: e.data.map(e => ({
              label: e.name,
              value: e.code,
            })),
          });
        },
      });
      this.props.dispatch({
        type: 'goodAdd/postObjWithRes',
        payload: {url:'/optshop/base/goodstype/searchAll',  brandId:  val.value },
        callback: (response:any) => {
          if (response) {
            this.setState({
              goodTypeOption: response.data.list.map((item:any)=>{
                return {
                  label: item.goodsTypeName,
                  value: item.goodsTypeId
                }
               }),
            });
          } else {
            this.setState({
              goodTypeOption: [],
            });
          }
        },
      });
      if(sessionStorage.getItem('goodsaleInfo')){
        const goodsaleInfo = JSON.parse(sessionStorage.getItem('goodsaleInfo') || '{}');
        goodsaleInfo['attributeList']=[];
        sessionStorage.setItem('goodsaleInfo', JSON.stringify(goodsaleInfo));
      }
  }
  onSeriesChange=()=>{
    this.formRef.current?.resetFields(['carTypes']);
    this.setState({ typeOptions: [] });
    const brandId = this.formRef.current?.getFieldValue('brandId');
    const seriesId = this.formRef.current?.getFieldValue('carSeries');
    brandId &&
      seriesId &&
      this.props.dispatch({
        type: 'goodAdd/getDataWithRes',
        payload: {
          url: '/common/vehicle/gettypelist',
          brandId: brandId.value,
          seriesId,
        },
        callback: e => {
          this.setState({
            typeOptions: e.data.map(e => ({
              label: e.name,
              value: e.code,
            })),
          });
        },
      });
  }
  getSeries=(brandId:any)=>{
    brandId &&
      this.props.dispatch({
        type: 'goodAdd/getDataWithRes',
        payload: {
          url: '/common/vehicle/getserieslist',
          brandId,
        },
        callback: (e:any) => {
          this.setState({
            seriesOptions: e.data.map((e:any) => ({
              label: e.name,
              value: e.code,
            })),
          });
        },
      });
  }
  getType=(brandId:any, seriesId:any)=>{
    brandId &&
      seriesId &&
      this.props.dispatch({
        type: 'goodAdd/getDataWithRes',
        payload: {
          url: '/common/vehicle/gettypelist',
          brandId,
          seriesId,
        },
        callback: e => {
          this.setState({
            typeOptions: e.data.map((e:any) => ({
              label: e.name,
              value: e.code,
            })),
          });
        },
      });
  }
  onTypeChange=(val:any)=>{
     //获取附属属性名称下拉框数据--根据商品类型查询附属属性
     const brandId = this.formRef.current?.getFieldValue('brandId');
     this.props.dispatch({
      type: 'goodAdd/getDataWithRes',
      payload: {url:'/optshop/base/subsidiary/attribute/select/affiliated/attributes',  goodsTypeId:  val, brandId: brandId.value },
      callback: (response:any) => {
        const list = response.data.list;
        const {getattributeList}=this.props;
        getattributeList(list);
      },
    });
    if(sessionStorage.getItem('goodsaleInfo')){
      const goodsaleInfo = JSON.parse(sessionStorage.getItem('goodsaleInfo') || '{}');
      goodsaleInfo['attributeList']=[];
      sessionStorage.setItem('goodsaleInfo', JSON.stringify(goodsaleInfo));
    }
  }
  getAttributeList = (goodsTypeId:any , brandId:any)=>{
     //获取附属属性名称下拉框数据--根据商品类型查询附属属性
     this.props.dispatch({
      type: 'goodAdd/getDataWithRes',
      payload: {url:'/optshop/base/subsidiary/attribute/select/affiliated/attributes', goodsTypeId,brandId },
      callback: (response:any) => {
        const list = response.data.list;
        const {getattributeList}=this.props;
        getattributeList(list);
      },
    });
  }
  //根据品牌获取商品类型下拉数据
  getGoodType = (val:any)=>{
    this.props.dispatch({
      type: 'goodAdd/postObjWithRes',
      payload: {url:'/optshop/base/goodstype/searchAll',  brandId:  val },
      callback: (response:any) => {
        if (response) {
          this.setState({
            goodTypeOption: response.data.list.map((item:any)=>{
              return {
                label: item.goodsTypeName,
                value: item.goodsTypeId
              }
             }),
          });
        } else {
          this.setState({
            goodTypeOption: [],
          });
        }
      },
    });
  }
  render() {
    const { fileList, pic, icon ,goodsQrPic, brandOptions,seriesOptions,typeOptions,goodTypeOption} = this.state;
    const fileurl = '/common/upload/all';
    const filestr = `${windowUrl}${fileurl}`;
    let md5 = getMd5('bizType=m18')
    // 禁用今天之前的日期
    const disabledDate = (current:any) => {
      return current && current < moment().startOf('day');
    };
    const platformOptions = getDictOptionsByCode(this.context.dicData, 'goodsPlatform');
    const isHotOptions = getDictOptionsByCode(this.context.dicData, 'isHot');
    const ifSendBySupplierOptions = getDictOptionsByCode(this.context.dicData, 'ifSendBySupplier');
    const payTypeOptions = getDictOptionsByCode(this.context.dicData, 'payTypes');
    const buyersOptions = getDictOptionsByCode(this.context.dicData, 'buyers');
    return (
      <Card>
        <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.nextPage}>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
               label="品牌"
               name="brandId"
               rules={[{ required: true, message: '请选择品牌' }]}
              >
                <Select 
                placeholder="请选择品牌"
                getPopupContainer={triggerNode => triggerNode.parentNode} 
                options={brandOptions}
                onChange={this.onBrandChange}
                disabled
                labelInValue
                />
              </FormItem>
          </Col>
          <Col span={8}>
              <FormItem
                label="车系"
                name="carSeries"
                rules={[{ required: true, message: '请选择车系' }]}
                >
                <Select 
                 placeholder="请选择车系"
                 getPopupContainer={triggerNode => triggerNode.parentNode} 
                 options={seriesOptions} 
                 onChange={this.onSeriesChange}
                 disabled
                 />
              </FormItem>
          </Col>
          <Col span={8}>
             <FormItem
               label="车型"
               name="carTypes"
               rules={[{ required: false, message: '请选择车型' }]}
             >
               <Select 
                 placeholder="请选择车型"
                 showSearch optionFilterProp="children" mode='multiple'
                 getPopupContainer={triggerNode => triggerNode.parentNode} 
                 options={typeOptions} 
                 />
              </FormItem>
          </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
               label="商品类型"
               name="goodsTypeId"
               rules={[{ required: true, message: '请选择商品类型' }]}
              >
                <Select 
                placeholder="请选择商品类型"
                getPopupContainer={triggerNode => triggerNode.parentNode} 
                disabled
                options={goodTypeOption} 
                onChange={this.onTypeChange}
                />
              </FormItem>
          </Col>
          <Col span={8}>
          <FormItem
                label="商品名称"
                name="spuName"
                rules={[{ required: true, message: '请输入商品名称' }]}
                >
                 <Input placeholder="请输入商品名称" maxLength={80}/>
              </FormItem>
          </Col>
          <Col span={8}>
             <FormItem
               label="商品编号"
               name="spuId"
             >
                <Input placeholder="请输入商品编号" disabled />
              </FormItem>
          </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
            <FormItem
               label="商品总量"
               name="spuTotalAmount"
               rules={[{ required: false, message: '请输入大于1的整数', pattern: new RegExp(/^[1-9]\d*$/, "g"), }]}
              >
                 <Input placeholder="请输入商品总量" />
              </FormItem>
          </Col>
          <Col span={8}>
          <FormItem
                label="有效期"
                name="validDate"
                rules={[{ required: false, message: '请输入有效期' }]}
                >
                   <DatePicker
                    format={'YYYY-MM-DD'} 
                    style={{ width: '100%' }}
                    placeholder="请输入有效期"
                    disabledDate={disabledDate}
                    />
              </FormItem>
          </Col>
           <Col span={8}>
           <FormItem
               label="商品平台"
               name="goodsPlatform"
               rules={[{ required: true, message: '请选择商品平台' }]}
             >
               <Select 
                 placeholder="请选择商品平台"
                 showSearch optionFilterProp="children" mode='multiple'
                 getPopupContainer={triggerNode => triggerNode.parentNode} 
                 options={platformOptions} />
              </FormItem>
          </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
            <FormItem
               label="是否供应商发货"
               name="ifSendBySupplier"
               rules={[{ required: true, message: '请选择是否供应商发货' }]}
              >
                 <Select 
                 placeholder="请选择是否供应商发货"
                 getPopupContainer={triggerNode => triggerNode.parentNode} 
                 options={ifSendBySupplierOptions} />
              </FormItem>
          </Col>
          <Col span={8}>
          <FormItem
                label="支付方式"
                name="payType"
                rules={[{ required: false, message: '请输入有效期' }]}
                >
                <Select 
                 placeholder="请选择支付方式"
                 getPopupContainer={triggerNode => triggerNode.parentNode} 
                 options={payTypeOptions} />
              </FormItem>
          </Col>
           <Col span={8}>
           <FormItem
               label="是否热门"
               name="isHot"
               rules={[{ required: true, message: '请选择是否热门' }]}
             >
               <Select 
                 placeholder="请选择是否热门"
                 getPopupContainer={triggerNode => triggerNode.parentNode} 
                 options={isHotOptions} />
              </FormItem>
          </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
            <FormItem
               label="商品最高价格"
               name="goodsMaxPrice"
               rules={[{ required: false, message: '请输入商品最高价格',pattern: /^[0-9]+(.[0-9]{1,2})?$/  }]}
              >
                 <Input placeholder="请输入商品最高价格"  maxLength={40}/>
              </FormItem>
          </Col>
          <Col span={8}>
          <FormItem
                label="购买人群"
                name="buyers"
                rules={[{ required: true, message: '请选择购买人群' }]}
                >
                <Select 
                 placeholder="请选择购买人群"
                 getPopupContainer={triggerNode => triggerNode.parentNode} 
                 options={buyersOptions} />
              </FormItem>
          </Col>
          <Col span={8}>
          <FormItem
               label="权益"
               name="benefits"
               rules={[{ required: false, message: '请输入权益' }]}
              >
               <Input placeholder="请输入权益" maxLength={400}/>
              </FormItem>
          </Col>
          </Row>
          <Row gutter={24}>
              <Col span={8}>
              <FormItem
               label="商品类目名称"
               name="goodsCategoryName"
               rules={[{ required: false, message: '请输入商品类目名称' }]}
              >
               <Input placeholder="请输入商品类目名称" maxLength={40}/>
              </FormItem>
          </Col>
          </Row>
          <Row gutter={24}>
          <Col span={8}>
              <FormItem
               label="商品状态"
               name="spuStatus"
              >
                 <Input placeholder="请输入商品最高价格" disabled/>
              </FormItem>
          </Col>
          <Col span={8}>
              <FormItem
               label="上架日期"
               name="saleTime"
              >
                 <Input placeholder="请输入上架日期" disabled/>
              </FormItem>
          </Col>
          <Col span={8}>
              <FormItem
               label="下架日期"
               name="endTime"
              >
                 <Input placeholder="请输入下架日期" disabled/>
              </FormItem>
          </Col>
          </Row>
          <Row gutter={24}>
          <Col span={16}>
             <FormItem
               label="商品描述"
               name="goodsDesc"
               rules={[{ required: true, message: '请输入商品描述' }]}
              >
              <TextArea style={{ minHeight: 32,width:'100%' }} maxLength={120} placeholder="请输入120字以内商品描述" rows={3} />
              </FormItem>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
            <FormItem
               label="商品图片"
               name="pic"
               rules={[{ required: true, message: '请上传商品图片' }]}
               valuePropName='fileList'
              >
               <PicturesWall
                data={pic}
                setPicture={this.setPic}
              />
              </FormItem>
            </Col>
            <Col span={8}>
            <FormItem
               label="商品图标"
               name="icon"
               rules={[{ required: false, message: '请上传商品图标' }]}
               valuePropName='fileList'
              >
              <PicturesWall
                data={icon}
                setPicture={this.setIcon}
              />
              </FormItem>
            </Col>
            <Col span={8}>
            <FormItem
               label="商品附件"
               name="goodsAttachment"
               rules={[{ required: false, message: '请上传商品附件' }]}
              >
              <>
               <Upload
                    action={filestr}
                    headers= {{
                      OptAuthorization: `${getToken()}`,
                      ...getOptAuthHeaders(),
                      shaSign: md5,
                    }
                    }
                    onChange={this.handleFileChange}
                    multiple={false}
                    fileList={fileList}
                    accept=" .zip"
                    beforeUpload={this.beforeFileUpload}
                  >{
                    fileList?.length == 0 ? (
                      <Button icon={<UploadOutlined />}>
                          请选择上传压缩包
                      </Button>
                    ) : null
                  }
               </Upload>
              <span style={{margin: 7}}>
              {
                this.state.fileList?.length == 0 ? (
                  <span style={{fontSize: 12}}>压缩包格式支持：.zip,单个包大小：小于20Mb</span>
                ) : (
                  fileList[0].size && <span style={{fontSize: 12}}>{"压缩包大小" + (fileList[0].size / 1024 / 1024).toFixed(2) + "Mb"}</span>
                )
              }
              </span>
              </>
              </FormItem>
            </Col>
          </Row>
          <Row>
          <Col span={8}>
            <FormItem
               label="商品二维码图片"
               name="goodsQrPic"
               rules={[{ required: false, message: '请上传商品二维码图片' }]}
               valuePropName='fileList'
              >
              <PicturesWall
                data={goodsQrPic}
                setPicture={this.setQrcode}
              />
              </FormItem>
            </Col>
          </Row>
          <Button type="primary" style={{float:'right'}}  htmlType="submit">下一步</Button>
        </Form>
      </Card>
    );
  }
}

export default basicInfo;
